package com.lc.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;

/**
 * Author:LiChuang
 * Date: 2022/8/5 15:20
 */
@Slf4j
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    private final static Logger LOG = LoggerFactory.getLogger(MyGlobalFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //System.out.println("路径：" + path);
        String name = request.getMethod().name();
        //System.out.println("请求方式：" + name);
        LOG.info("请求方式->>>>>>>>>>>>>>>>>>>>>>>>：" + name);
        String ip = request.getHeaders().getHost().getHostString();
        //System.out.println("ip地址：" + ip);

        /*
        用了微服务 肯定是前后端分离的 前后端分离 一般前后通过 json
        {"code":200,"msg":"ok"}
         */
        //ServerHttpResponse response = exchange.getResponse();
        //response.getHeaders().set("content-type", "application/json;charset=utf-8");
        //HashMap<String, Object> map = new HashMap<>();
        //map.put("code", HttpStatus.BAD_REQUEST.value());
        //map.put("msg", "未经注册");
        //ObjectMapper objectMapper = new ObjectMapper();
        //byte[] bytes = new byte[0];
        //try {
        //    bytes = objectMapper.writeValueAsBytes(map);
        //} catch (JsonProcessingException e) {
        //    e.printStackTrace();
        //}
        //DataBuffer wrap = response.bufferFactory().wrap(bytes);
        //return response.writeWith(Mono.just(wrap));

        //放行到下一个过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 5;
    }
}
